package com.iaiai.browser.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;

/**
 * 
 * <p>
 * Title: HttpUtil.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2011-7-11
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class HttpUtil {

	public interface CallBack {
		void onRead(InputStream input);
	}

	private static String cookies; // cookie

	/**
	 * 判断是否是url
	 * 
	 * @param url
	 * @return true是url，false不是url
	 */
	public static boolean isUrl(String url) {
		try {
			URL u = new URL("http://www.baidu.com");
			InputStream in = u.openStream();
			in.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static Spanned fromHtml(String value) {
		ImageGetter imgGetter = new Html.ImageGetter() {
			public Drawable getDrawable(String source) {
				Drawable drawable = null;
				drawable = Drawable.createFromPath(source);
				// Important
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
				return drawable;
			}
		};
		// return Html.fromHtml(value, imgGetter, null);
		return Html.fromHtml(value);
	}

	/**
	 * http访问数据，默认返回的数据为UTF-8编码
	 * 
	 * @param url
	 *            url地址
	 * @return
	 * @throws IOException
	 */
	public static String getUrl(String url) throws IOException {
		HttpGet request = getHttpGet(url);
		if (cookies != null)
			request.setHeader("Cookie", cookies);
		HttpClient httpClient = getHttpClient();
		HttpResponse response = httpClient.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return EntityUtils.toString(response.getEntity());
		} else {
			throw new IOException(response.getStatusLine().getStatusCode() + "");
		}
	}

	private static HttpGet getHttpGet(String url) {
		HttpGet request = new HttpGet(url);
		request.addHeader("Pragma", "no-cache");
		request.addHeader("Cache-Control", "no-cache");
		return request;
	}

	private static HttpClient getHttpClient() {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); // 设置请求超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				30000); // 读取超时
		return httpClient;
	}

	/**
	 * 登录
	 * 
	 * @param url
	 *            登录地址
	 * @param params
	 *            参数
	 * @return
	 * @throws IOException
	 */
	public static String login(String url, Map<String, String> params)
			throws IOException {
		if (url.indexOf("?") > 0) { // 判断是否有参数
			String headUrl = url.substring(0, url.indexOf("?")); // ?号前的地址
			String paramsUrl = url.substring(url.indexOf("?") + 1); // ?号后的参数

			if (paramsUrl == null || paramsUrl.length() <= 0) {
				url = url + "&" + getParameterUrl(params);
			}

			paramsUrl = paramsUrl.endsWith("&") ? paramsUrl : paramsUrl + "&"; // 判断结尾是否有&号，如果没有则加上
			url = url + "?" + paramsUrl + getParameterUrl(params);
		}

		if (params.size() > 0) { // 如果有参数
			url = url + "?" + getParameterUrl(params);
		}

		HttpGet request = getHttpGet(url);
		HttpClient httpClient = getHttpClient();
		HttpResponse response = httpClient.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			cookies = response.getFirstHeader("Set-Cookie").getValue();
			return EntityUtils.toString(response.getEntity());
		} else {
			return "";
		}
	}

	/**
	 * ttp访问数据，默认返回的数据为UTF-8编码
	 * 
	 * @param url
	 *            url地址
	 * @param params
	 *            参数
	 * @return
	 * @throws IOException
	 */
	public static String getUrl(String url, Map<String, String> params)
			throws IOException {
		if (url.indexOf("?") > 0) { // 判断是否有参数
			String headUrl = url.substring(0, url.indexOf("?")); // ?号前的地址
			String paramsUrl = url.substring(url.indexOf("?") + 1); // ?号后的参数

			if (paramsUrl == null || paramsUrl.length() <= 0) {
				return getUrl(url + "&" + getParameterUrl(params));
			}

			paramsUrl = paramsUrl.endsWith("&") ? paramsUrl : paramsUrl + "&"; // 判断结尾是否有&号，如果没有则加上
			return getUrl(url + "?" + paramsUrl + getParameterUrl(params));
		}

		if (params.size() > 0) { // 如果有参数
			return getUrl(url + "?" + getParameterUrl(params));
		}
		return getUrl(url);
	}

	/**
	 * 访问地址并返回留数据
	 * 
	 * @param url
	 * @param params
	 * @param callBack
	 * @throws IOException
	 */
	public static void getUrl(String url, Map<String, String> params,
			CallBack callBack) throws IOException {
		String uri = url;
		if (url.indexOf("?") > 0) { // 判断是否有参数
			String headUrl = url.substring(0, url.indexOf("?")); // ?号前的地址
			String paramsUrl = url.substring(url.indexOf("?") + 1); // ?号后的参数

			if (paramsUrl == null || paramsUrl.length() <= 0) {
				uri = url + "&" + getParameterUrl(params);
			}

			paramsUrl = paramsUrl.endsWith("&") ? paramsUrl : paramsUrl + "&"; // 判断结尾是否有&号，如果没有则加上
			uri = url + "?" + paramsUrl + getParameterUrl(params);
		}

		if (params.size() > 0) { // 如果有参数
			uri = url + "?" + getParameterUrl(params);
		}

		HttpGet request = getHttpGet(uri);
		if (cookies != null)
			request.setHeader("Cookie", cookies);
		HttpClient httpClient = getHttpClient();
		HttpResponse response = httpClient.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			callBack.onRead(response.getEntity().getContent());
		}
	}

	/**
	 * 把所有参数拼成字符串
	 * 
	 * @param params
	 *            参数
	 * @return
	 */
	private static String getParameterUrl(Map<String, String> params) {
		if (params.size() <= 0) {
			return "";
		}
		StringBuilder paramUrl = new StringBuilder();
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> entry = iterator.next();
			paramUrl.append("&").append(entry.getKey()).append("=")
					.append(entry.getValue());
		}
		return paramUrl.toString().substring(1);
	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postUrl(String url, Map<String, String> params)
			throws ClientProtocolException, IOException {
		return postUrl(url, params, "UTF-8");
	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void postUrl(String url, Map<String, String> params,
			CallBack callBack) throws ClientProtocolException, IOException {
		List<NameValuePair> param = new ArrayList<NameValuePair>(); // 参数
		// param.add(new BasicNameValuePair("par", "request-post"));
		// //这个参数我不知道是不是非要加这个

		// 添加参数
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> entry = iterator.next();

			param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}

		HttpPost request = new HttpPost(url);
		if (cookies != null)
			request.setHeader("Cookie", cookies);
		HttpEntity entity = new UrlEncodedFormEntity(param, "UTF-8");
		request.setEntity(entity);

		HttpClient client = getHttpClient();

		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			callBack.onRead(response.getEntity().getContent());
		}
	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            参数
	 * @param encoding
	 *            参数编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postUrl(String url, Map<String, String> params,
			String encoding) throws ClientProtocolException, IOException {
		List<NameValuePair> param = new ArrayList<NameValuePair>(); // 参数
		// param.add(new BasicNameValuePair("par", "request-post"));
		// //这个参数我不知道是不是非要加这个

		// 添加参数
		Iterator<String> iterator = params.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			if (key == null)
				continue;
			param.add(new BasicNameValuePair(key, params.get(key)));
		}

		HttpPost request = new HttpPost(url);
		if (cookies != null)
			request.setHeader("Cookie", cookies);
		HttpEntity entity = new UrlEncodedFormEntity(param, encoding);
		request.setEntity(entity);

		HttpClient client = getHttpClient();

		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return EntityUtils.toString(response.getEntity());
		} else {
			return null;
		}
	}

}
